package com.h3c.ptability.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.h3c.ptability.config.SpringUtil;
import com.h3c.ptability.config.mq.LogRabbitConfig;
import com.h3c.ptability.dto.PtUploadFileDTO;
import com.h3c.ptability.entity.PtAllWorker;
import com.h3c.ptability.entity.PtUploadFile;
import com.h3c.ptability.entity.SdFileOperLog;
import com.h3c.ptability.mapper.PtAllWorkerMapper;
import com.h3c.ptability.mapper.PtUploadFileMapper;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IPtUploadFileService;
import com.h3c.ptability.utils.AppBusinessException;
import com.h3c.ptability.utils.InitExampleOrderByUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtUploadFileServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_upload_file serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtUploadFileServiceImpl extends ServiceImpl<PtUploadFileMapper, PtUploadFile> implements IPtUploadFileService {

    @Resource
    private PtUploadFileMapper ptUploadFileMapper;

    @Autowired
    private LogRabbitConfig logRabbitConfig;

    @Autowired
    PtAllWorkerMapper ptAllWorkerMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    CommService commService;

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtUploadFileDTO> selectFuzzyByDto(PtUploadFileDTO dto) {
//        //List<PtUploadFile> list = ptUploadFileMapper.selectByExample(initFuzzyExample(dto));
//        List<PtUploadFile> list = ptUploadFileMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtUploadFile.class));
//        return JSONArray.parseArray(JSONArray.toJSONString(list), PtUploadFileDTO.class);
        //List<PtUploadFile> list = PtUploadFileMapper.selectByExample(initFuzzyExample(dto));
        QueryWrapper<PtUploadFile> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(dto.getOperatorId())) {
            queryWrapper.in("operator_id", Arrays.asList(dto.getOperatorId().split(",")));
        }
        queryWrapper.eq(StringUtils.hasLength(dto.getBusiType()), "busi_type", dto.getBusiType());
        queryWrapper.like(StringUtils.hasLength(dto.getFileName()), "file_name", dto.getFileName());

        queryWrapper.eq("app_id", dto.getAppId());
        List<PtUploadFile> fileList = ptUploadFileMapper.selectList(queryWrapper);
        //List<PtUploadFile> list = PtUploadFileMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtUploadFile.class));
        List<String> workerIdList = fileList.stream().map(PtUploadFile::getOperatorId).distinct().collect(Collectors.toList());
        List<PtAllWorker> workers = ptAllWorkerMapper.selectList(new QueryWrapper<PtAllWorker>().lambda().in(PtAllWorker::getWorkerId, workerIdList));
        Map<String, String> map = workers.stream().collect(Collectors.toMap(PtAllWorker::getWorkerId, i -> i.getWorkerName() + "/" + i.getWorkerId()));
        fileList.forEach(file -> {
            String operatorId = file.getOperatorId();
            file.setOperatorId(map.getOrDefault(operatorId, operatorId));
        });
        return JSONArray.parseArray(JSONArray.toJSONString(fileList), PtUploadFileDTO.class);
    }

    public List<PtUploadFileDTO> queryFileOrderByTime(PtUploadFileDTO dto) {
//        //List<PtUploadFile> list = ptUploadFileMapper.selectByExample(initFuzzyExample(dto));
//        List<PtUploadFile> list = ptUploadFileMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtUploadFile.class));
//        return JSONArray.parseArray(JSONArray.toJSONString(list), PtUploadFileDTO.class);
        //List<PtUploadFile> list = PtUploadFileMapper.selectByExample(initFuzzyExample(dto));
        QueryWrapper<PtUploadFile> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(dto.getOperatorId())) {
            queryWrapper.in("operator_id", Arrays.asList(dto.getOperatorId().split(",")));
        }
        queryWrapper.like(StringUtils.hasLength(dto.getBusiType()), "busi_type", dto.getBusiType());
        queryWrapper.like(StringUtils.hasLength(dto.getFileName()), "file_name", dto.getFileName());

        queryWrapper.eq("app_id", dto.getAppId());
        queryWrapper.orderByDesc("upload_time");
        List<PtUploadFile> fileList = ptUploadFileMapper.selectList(queryWrapper);
        fileList.forEach(i -> i.setOperatorId(commService.getLoginUserIdWithNoException()));
        return JSONArray.parseArray(JSONArray.toJSONString(fileList), PtUploadFileDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtUploadFileDTO> selectByDto(PtUploadFileDTO dto) {
        //List<PtUploadFile> list = ptUploadFileMapper.selectByExample(initExample(dto));
        List<PtUploadFile> list = ptUploadFileMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto),PtUploadFile.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtUploadFileDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(PtUploadFileDTO dto) {
        if (!StringUtils.hasLength(dto.getFileId())) {
            dto.setFileId(String.valueOf(IdWorker.nextId()));
        }
        dto.setUploadTime(new Date());
        return ptUploadFileMapper.insertPtUploadFile(JSONObject.parseObject(JSON.toJSONString(dto), PtUploadFile.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(PtUploadFileDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
//            QueryWrapper<PtUploadFile> queryWrapper = Wrappers.query();
//            PtUploadFile uploadFile = ptUploadFileMapper.selectOne(queryWrapper.eq("file_url", dto.getFileUrl()));
//            if (uploadFile != null){
//                throw new AppBusinessException("该链接已存在，请重新输入");
//            }
        PtUploadFile ptUploadFile = new PtUploadFile();
        BeanUtils.copyProperties(dto, ptUploadFile);
        ptUploadFile.setUploadTime(new Date());
        return ptUploadFileMapper.update(ptUploadFile, new QueryWrapper<PtUploadFile>().eq("file_url", dto.getFileUrl()));
//      return ptUploadFileMapper.updatePtUploadFile(JSONObject.parseObject(JSON.toJSONString(dto), PtUploadFile.class));
        //return ptUploadFileMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), PtUploadFile.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(PtUploadFileDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        SpringUtil.getBean(CommService.class).deleteSfsFile(dto.getFileId());//sFs
        return ptUploadFileMapper.deletePtUploadFile(JSONObject.parseObject(JSON.toJSONString(dto), PtUploadFile.class));
            //return ptUploadFileMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(PtUploadFileDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtUploadFile.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getFileId() && !"".equals(dto.getFileId())) {
                criteriaName.andLike("FileId", "%" + dto.getFileId() + "%");
            }
            if (null != dto.getAppId() && !"".equals(dto.getAppId())) {
                criteriaName.andLike("AppId", "%" + dto.getAppId() + "%");
            }
            if (null != dto.getBusiType() && !"".equals(dto.getBusiType())) {
                criteriaName.andLike("BusiType", "%" + dto.getBusiType() + "%");
            }
            if (null != dto.getFileName() && !"".equals(dto.getFileName())) {
                criteriaName.andLike("FileName", "%" + dto.getFileName() + "%");
            }
            if (null != dto.getOperatorId() && !"".equals(dto.getOperatorId())) {
                criteriaName.andLike("OperatorId", "%" + dto.getOperatorId() + "%");
            }
            if (null != dto.getUploadTime() && !"".equals(dto.getUploadTime())) {
                criteriaName.andLike("UploadTime", "%" + dto.getUploadTime() + "%");
            }
            if (null != dto.getBusiId() && !"".equals(dto.getBusiId())) {
                criteriaName.andLike("BusiId", "%" + dto.getBusiId() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(PtUploadFileDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtUploadFile.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getFileId() && !"".equals(dto.getFileId())) {
                criteriaName.andEqualTo("FileId", dto.getFileId());
            }
            if (null != dto.getAppId() && !"".equals(dto.getAppId())) {
                criteriaName.andEqualTo("AppId", dto.getAppId());
            }
            if (null != dto.getBusiType() && !"".equals(dto.getBusiType())) {
                criteriaName.andEqualTo("BusiType", dto.getBusiType());
            }
            if (null != dto.getFileName() && !"".equals(dto.getFileName())) {
                criteriaName.andEqualTo("FileName", dto.getFileName());
            }
            if (null != dto.getOperatorId() && !"".equals(dto.getOperatorId())) {
                criteriaName.andEqualTo("OperatorId", dto.getOperatorId());
            }
            if (null != dto.getUploadTime() && !"".equals(dto.getUploadTime())) {
                criteriaName.andEqualTo("UploadTime", dto.getUploadTime());
            }
            if (null != dto.getBusiId() && !"".equals(dto.getBusiId())) {
                criteriaName.andEqualTo("BusiId", dto.getBusiId());
            }
        }
        return example;
    }

    @Override
    public void saveUploadHistory(MultipartFile uploadFile, String appId, String busiId, String operatorId, String operatorName, String ip, String fileName) {
        SdFileOperLog requestLog = new SdFileOperLog();
        requestLog.setFileLogId(IdWorker.nextId() + "");
        requestLog.setAppId(appId);
        requestLog.setOperUserId(operatorId);
        requestLog.setOperUserName(operatorName);
        requestLog.setOperTime(new Date());
        requestLog.setOperIp(ip);
        requestLog.setFileName(fileName);
        requestLog.setOperType("IMPORT");
        requestLog.setFileSize(new BigDecimal(uploadFile.getSize()));
        Message message = logRabbitConfig.getMessage(JSONObject.toJSONString(requestLog));
        rabbitTemplate.convertAndSend(logRabbitConfig.getExchange(), logRabbitConfig.getFileOperLogQueue(), message);


    }

    @Override
    public Integer deleteUrlData(PtUploadFileDTO paramsDTO) {
        return ptUploadFileMapper.delete(new QueryWrapper<PtUploadFile>().eq("file_url", paramsDTO.getFileUrl()));
    }
}
